<template>
  <div class="maintenance-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>维护记录</span>
          <el-button type="primary" @click="$router.push('/maintenance/add')">
            添加维护
          </el-button>
        </div>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="资产名称">
            <el-input v-model="searchForm.assetName" placeholder="请输入资产名称" clearable />
          </el-form-item>
          <el-form-item label="维护类型">
            <el-select v-model="searchForm.type" placeholder="请选择维护类型" clearable>
              <el-option label="定期维护" value="定期维护"></el-option>
              <el-option label="故障维修" value="故障维修"></el-option>
              <el-option label="预防性维护" value="预防性维护"></el-option>
              <el-option label="紧急维修" value="紧急维修"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="维护状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待维护" value="待维护"></el-option>
              <el-option label="维护中" value="维护中"></el-option>
              <el-option label="已完成" value="已完成"></el-option>
              <el-option label="已取消" value="已取消"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="维护日期">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        size="small"
      >
        <el-table-column type="selection" width="45" />
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="assetName" label="资产名称" width="120" show-overflow-tooltip />
        <el-table-column prop="assetCode" label="资产编码" width="100" />
        <el-table-column prop="type" label="维护类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)" size="small">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="maintainer" label="维护人员" width="80" />
        <el-table-column prop="startDate" label="开始日期" width="100" />
        <el-table-column prop="endDate" label="完成日期" width="100" />
        <el-table-column prop="cost" label="维护费用" width="80">
          <template #default="scope">
            ¥{{ scope.row.cost }}
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="scope">
            <el-tag :type="getPriorityTagType(scope.row.priority)" size="small">
              {{ scope.row.priorityText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="维护描述" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <div class="table-actions">
              <div class="action-row">
                <el-button 
                  link 
                  size="small" 
                  @click="viewDetail(scope.row)"
                >
                  查看
                </el-button>
                <el-button 
                  link 
                  size="small" 
                  @click="editRecord(scope.row)"
                  :disabled="scope.row.status === '已完成'"
                >
                  编辑
                </el-button>
              </div>
              <div class="action-row">
                <el-button 
                  link 
                  size="small" 
                  @click="startMaintenance(scope.row)"
                  v-if="scope.row.status === '待维护'"
                >
                  开始维护
                </el-button>
                <el-button 
                  link 
                  size="small" 
                  @click="completeMaintenance(scope.row)"
                  v-if="scope.row.status === '维护中'"
                >
                  完成维护
                </el-button>
                <el-button 
                  link 
                  size="small" 
                  @click="deleteRecord(scope.row)"
                  :disabled="scope.row.status === '维护中'"
                >
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedRows.length > 0">
        <el-button @click="batchDelete">批量删除</el-button>
        <el-button @click="batchExport">批量导出</el-button>
        <el-button @click="batchUpdateStatus">批量更新状态</el-button>
      </div>
    </el-card>
    
    <!-- 维护详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="维护详情"
      width="800px"
    >
      <div v-if="currentRecord" class="maintenance-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="维护ID">{{ currentRecord.id }}</el-descriptions-item>
          <el-descriptions-item label="资产名称">{{ currentRecord.assetName }}</el-descriptions-item>
          <el-descriptions-item label="资产编码">{{ currentRecord.assetCode }}</el-descriptions-item>
          <el-descriptions-item label="维护类型">
            <el-tag :type="getTypeTagType(currentRecord.type)">{{ currentRecord.type }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="维护状态">
            <el-tag :type="getStatusTagType(currentRecord.status)">{{ currentRecord.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTagType(currentRecord.priority)" size="small">
              {{ priorityText(currentRecord.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="维护人员">{{ currentRecord.maintainer }}</el-descriptions-item>
          <el-descriptions-item label="计划日期">{{ currentRecord.planDate }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ currentRecord.startDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="完成日期">{{ currentRecord.endDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="维护费用">¥{{ currentRecord.cost }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentRecord.createTime }}</el-descriptions-item>
          <el-descriptions-item label="维护描述" :span="2">
            {{ currentRecord.description }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 维护进度 -->
        <div class="maintenance-progress">
          <h4>维护进度</h4>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in currentRecord.progress"
              :key="index"
              :timestamp="activity.time"
              :type="activity.type"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { maintenanceApi, assetApi, userApi } from '@/api'
import { MaintStatusTextToCode, MaintStatusCodeToText } from '@/utils/status'

const router = useRouter()
const loading = ref(false)
const detailVisible = ref(false)
const currentRecord = ref<any>(null)
const selectedRows = ref<any[]>([])

// 搜索表单
const searchForm = ref({
  assetName: '',
  type: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])

// 缓存资产 / 用户信息
const assetMap = ref<Record<number, any>>({})
const userMap = ref<Record<number, any>>({})

// 预加载资产和用户
const preloadRefData = async () => {
  try {
    const [assetRes, users] = await Promise.all([
      assetApi.getList({ page: 1, size: 100 }),
      userApi.getAll()
    ])
    ;(assetRes.list || assetRes.records || []).forEach((a: any) => {
      assetMap.value[a.id] = a
    })
    ;(users || []).forEach((u: any) => {
      userMap.value[u.id] = u
    })
  } catch (err) {
    console.error('预加载资产/用户失败', err)
  }
}

const statusCodeMap: Record<string, number> = {
  '待维护': 0,
  '维护中': 1,
  '已完成': 2,
  '已取消': 3
}

const statusTextMap: Record<number, string> = {
  0: '待维护',
  1: '维护中',
  2: '已完成',
  3: '已取消'
}

const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    '定期维护': 'primary',
    '故障维修': 'danger',
    '预防性维护': 'success',
    '紧急维修': 'warning'
  }
  return typeMap[type] || 'info'
}

const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    '待维护': 'info',
    '维护中': 'warning',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const getPriorityTagType = (priority: number) => {
  const priorityMap: Record<number, string> = {
    1: 'danger', // 高
    2: 'warning', // 中
    3: 'info', // 低
    4: 'danger' // 紧急
  }
  return priorityMap[priority] || 'info'
}

const priorityText = (priority: number) => {
  const priorityMap: Record<number, string> = {
    1: '高', // 高
    2: '中', // 中
    3: '低', // 低
    4: '紧急' // 紧急
  }
  return priorityMap[priority] || '--'
}

const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    assetName: '',
    type: '',
    status: '',
    dateRange: []
  }
  handleSearch()
}

const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      current: pagination.value.current,
      size: pagination.value.size,
      assetName: searchForm.value.assetName,
      type: searchForm.value.type,
      status: searchForm.value.status ? MaintStatusTextToCode[searchForm.value.status] : undefined,
      startDate: searchForm.value.dateRange[0],
      endDate: searchForm.value.dateRange[1]
    }
    const res: any = await maintenanceApi.getList(params)
    const rows = res.list || res.records || []
    tableData.value = rows.map((r:any)=> ({
      ...r,
      assetName: assetMap.value[r.assetId]?.name || `#${r.assetId}`,
      assetCode: assetMap.value[r.assetId]?.code || '',
      maintainer: userMap.value[r.performedBy]?.username || `#${r.performedBy}`,
      status: MaintStatusCodeToText[r.status] || r.status,
      priorityText: ['高','中','低','紧急'][ (r.priority||0)-1 ] || '--',
      startDate: r.startDate || '',
      endDate: r.endDate || '',
    }))
    pagination.value.total = res.total || rows.length || 0
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size: number) => {
  pagination.value.size = size
  loadData()
}

const handleCurrentChange = (current: number) => {
  pagination.value.current = current
  loadData()
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const viewDetail = (row: any) => {
  currentRecord.value = row
  detailVisible.value = true
}

const editRecord = (row: any) => {
  router.push(`/maintenance/edit/${row.id}`)
}

const startMaintenance = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要开始维护"${row.assetName}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await maintenanceApi.updateStatus(row.id, 1)
    row.status = '维护中'
    row.startDate = new Date().toISOString().slice(0, 10)
    ElMessage.success('维护已开始')
  } catch {
    // 用户取消
  }
}

const completeMaintenance = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要完成维护"${row.assetName}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await maintenanceApi.updateStatus(row.id, 2)
    row.status = '已完成'
    row.endDate = new Date().toISOString().slice(0, 10)
    ElMessage.success('维护已完成')
  } catch {
    // 用户取消
  }
}

const deleteRecord = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除维护记录"${row.assetName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await maintenanceApi.delete(row.id)
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await maintenanceApi.batchDelete(selectedRows.value.map(r => r.id))
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    loadData()
  } catch {
    // 用户取消
  }
}

const batchExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要导出的记录')
    return
  }
  
  // 创建CSV内容
  const headers = ['维护ID', '资产名称', '维护类型', '维护状态', '维护人员', '开始时间', '结束时间', '维护费用', '维护结果']
  const csvContent = [
    headers.join(','),
    ...selectedRows.value.map(maintenance => [
      maintenance.id,
      maintenance.assetName,
      maintenance.type,
      maintenance.status,
      maintenance.maintainer,
      maintenance.startDate,
      maintenance.endDate,
      maintenance.cost,
      maintenance.status === '已完成' ? '成功' : '未完成'
    ].join(','))
  ].join('\n')
  
  // 创建下载链接
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', `维护记录_${new Date().toISOString().split('T')[0]}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success(`成功导出${selectedRows.value.length}条维护记录`)
}

const batchUpdateStatus = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要更新的记录')
    return
  }
  
  (ElMessageBox.prompt as any)('请输入新的状态', '批量更新状态', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'select',
    inputValue: '已完成',
    inputOptions: [
      { label: '待处理', value: '待处理' },
      { label: '进行中', value: '进行中' },
      { label: '已完成', value: '已完成' },
      { label: '已暂停', value: '已暂停' }
    ]
  } as any).then(({ value }: any) => {
    const code = statusCodeMap[value] ?? 0
    Promise.all(selectedRows.value.map(row => maintenanceApi.updateStatus(row.id, code)))
    selectedRows.value.forEach(row => {
      row.status = value
    })
    ElMessage.success(`成功更新${selectedRows.value.length}条记录的状态为"${value}"`)
    selectedRows.value = []
  }).catch(() => {
    ElMessage.info('已取消批量更新')
  })
}

onMounted(async () => {
  await preloadRefData()
  loadData()
})
</script>

<style scoped>
.maintenance-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  display: flex;
  gap: 10px;
}

.maintenance-detail {
  padding: 20px 0;
}

.maintenance-progress {
  margin-top: 30px;
}

.maintenance-progress h4 {
  margin: 0 0 15px 0;
  color: var(--text-color);
}

.table-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.action-row {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.action-row .el-button {
  padding: 4px 6px;
  font-size: 12px;
  min-width: auto;
}

/* 表格响应式优化 */
@media (max-width: 1200px) {
  .action-row {
    flex-direction: column;
    gap: 2px;
  }
  
  .action-row .el-button {
    padding: 2px 4px;
    font-size: 11px;
  }
}

@media (max-width: 768px) {
  .maintenance-list {
    padding: 10px;
  }
  
  .search-section {
    padding: 15px;
  }
  
  .search-section .el-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-section .el-form-item {
    margin-bottom: 10px;
  }
  
  .batch-actions {
    flex-direction: column;
  }
  
  /* 移动端表格优化 */
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px 4px;
  }
}
</style>